<?php

namespace app\index\controller;
use think\Db;
use app\index\model\User as UserModel;
use app\index\model\Order;
use app\index\model\Profile;
use think\Controller;
use think\Session;
use app\index\model\Account;
use app\index\model\Address;

class User extends Controller
{
    // 注册界面
    public function register()
    {
        $this->view->engine->layout(true);
        return $this->fetch();
    }
    // 登录页面
    public function login()
    {
        $this->view->engine->layout(true);
        return $this->fetch();
    }
    // 用户信息
    public function info()
    {
        $result = UserModel::get(['username' => session('name')]);
        // $this->view->engine->layout(true);
        $this->assign('result',$result);
        return $this->fetch();
    }
    // 用户订单信息
    public function order()
    {
        $order = Db::name('order')->where('user_id',session('id'))->select();
        $result = UserModel::get(['username' => session('name')]);
        $this->view->engine->layout(true);
        $this->assign('order',$order);
        return $this->fetch();
    }
    // 用户地址信息
    public function address()
    {
        // 获取地址遍历信息
        $address = Db::name('address')
                    ->where('user_id',session('id'))
                    ->order('ismain','desc')
                    ->select();
        $this->assign('data',$address);
        $this->assign('count',count($address));
        $result = UserModel::get(['username' => session('name')]);
        $this->assign('result',$result);
        $this->view->engine->layout(true);
        return $this->fetch();
    }
    // AJAX注册用户名验证
    public function nameAjax()
    {
        if (input('param.username')) {
            $username = input('param.username');
            $len = strlen($username);
            if ($len < 4 || $len > 20) {
              echo '用户名长度不在4-20范围内';
              exit;
            }
            $result = UserModel::get(['username' => $username]);
            // $result = UserModel::get(['username' => input('param.username')]);
            if ($result) {
              echo '该用户已被注册，返回重新填写';
            } else {
              echo '恭喜你，' . $username . '可以注册!';
            }
        }
    }
    // AJAX邮箱验证
    // public function emailAjax()
    // {
    //    $email = input('param.email');
    //    $reg = '/^[a-zA-Z0-9_-]+@[a-z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/';
    //    // $reg = '/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/';
    //    if (preg_match($reg, $email, $matches)) {
    //         echo '输入正确';
    //         exit();
    //     } else {
    //         echo '请输入正确的邮箱格式';
    //     }
    // }
    // AJAX手机号验证
    public function phoneAjax()
    {
        $moblie = input('param.phone');
        $reg = '/^1[34578]{1}\d{9}$/';
        if (preg_match($reg, $moblie, $matches)) {
            echo '';
        } else {
            echo '请输入正确的手机号码!';
        }
    }
    // AJAX密码检查
    public function pwdAjax()
    {
        $pwd = input('param.pwd');
        $len = strlen($pwd);
        $regpwd = '/\D+/';
        if (!preg_match($regpwd, $pwd, $matches)) {
            echo '密码不能为纯数字';
            exit;
        }
        // 密码长度验证
        if ($len < 6 || $len > 20) {
          echo '密码长度不在6-20范围内';
          exit;
        }
    }
    // AJAX密码二次验证
    public function confirmAjax()
    {
        $pwd = input('param.password');
        $confirm = input('param.confirm');
        if ($pwd != $confirm) {
            echo '输入的密码不一致';
        }
    }
    // AJAX登陆验证
    // 用户名验证
    public function loginNameAjax()
    {
        if (input('param.username')) {
            $username = input('param.username');
            $result = UserModel::get(['username' => $username]);
            if (!$result) {
              echo '用户名不存在';
            } else {
              echo '';
            }
        }
    }
    // 密码验证
    public function loginPwdAjax()
    {
        $password = md5(input('get.pwd'));
        $username = input('param.name');
        $pwd = UserModel::where('username',$username)->value('password');
        if ($password != $pwd) {
            echo '密码不正确';
        } else {
            echo '';
        }
    }
    // POST注册验证
    public function regCheck()
    {
        $request = request();
        if ($request->method() == 'POST') {
            // 检测用户名长度
            $len = strlen(input('param.username'));
            if ($len < 4 || $len > 20) {
                $this->error('用户名长度不在4-20范围内');
                exit();
            }
        }
        // 查询数据库，确认用户是否存在
        $result = UserModel::get(['username' => input('param.username')]);
        if ($result) {
            $this->error('该用户已被注册，返回重新填写');
            exit();
        }
        // // 邮箱验证
        // $reg = '/^[a-zA-Z0-9_-]+@[a-z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/';
        // if (!preg_match($reg, input('param.email'), $matches)) {
        //     $this->error('邮箱输入有误!');
        // }
        // 手机号验证
        $reg = '/^1[34578]{1}\d{9}$/';
        if (!preg_match($reg, input('param.phone'), $matches)) {
            $this->error('请输入正确的手机号码!');
        }
        // 检查密码以及确认密码
        if (empty(trim(input('param.password'))) || empty(trim(input('param.repassword')))) {
            $this->error('密码以及确认密码不能为空');
        }
        if (input('param.password') != input('param.repassword')) {
            $this->error('两次输入的密码不一致');
        }
         // 密码不能为纯数字
        $regpwd = '/\D+/';
        if (!preg_match($regpwd, input('param.password'), $matches)) {
            $this->error('密码不能为纯数字');
            exit();
        }
        // 验证码
        if(!captcha_check(input('param.yzm'))){
            $this->error('验证码输入有误');
        };
        // 准备写入数据
         $data = [];
         $data['username']= trim(input('param.username'));
         $data['password'] = md5(input('param.password'));
         $data['phone'] = input('param.phone');
         $data['create_ip'] = $_SERVER['REMOTE_ADDR'];
         $data['reg_time'] = $_SERVER['REQUEST_TIME_FLOAT'];
         if ($data['create_ip'] == '::1') {
             $data['create_ip'] = '127.0.0.1';
         }
         $data['create_ip'] = ip2long($data['create_ip']);
         $result = Db::name('user')->insert($data);
         if ($result) {


        $result1 = Db::name('user')->where('udertype',0)->order('reg_time desc' )->find();
        //var_dump($result1);
        //exit;
        $data1 = [];
        $data1['user_id'] = $result1['id'];
        $data1['lever'] = '普通会员';
        $data1['score'] = 10;
        $result = Db::name('account')->insert($data1);
        $this->success('注册成功','login');    

         } else {
            $this->error('注册失败');
         }
        // $this->error('请使用正确的方式打开');
    }
    // POST登陆验证
    public function loginCheck()
    {
        // 用户名密码检测
        $username = input('param.username');
        $pwd = md5(input('param.password'));
        $result = UserModel::get(['username' => $username]);
        if (!$result) {
            $this->error('用户名不存在');
            exit;
        }        
        if ($pwd != $result['password']) {
             $this->error('密码输入错误');
             exit;
        }
        // 验证码
        if(!captcha_check(input('param.yzm'))){
            $this->error('验证码输入有误');
        };
        // session赋值
        session('name', $result['username']);
        session('id',$result['id']);
        $this->redirect('/');
    }
    // 退出操作
    public function logout()
    {
        // 删除清空session
        session('name');
        session('id');
        session(null);
        $this->success('欢迎再次登陆','/');
    }
    // 用户头像上传
    public function upload(){
        // var_dump($_POST);
        // exit();
        // 获取表单上传文件 
        $file = request()->file('image');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>1048576,'ext'=>'jpg,png,gif,jpeg'])->rule('date')->move(ROOT_PATH . 'public' . DS . 'images' . DS . 'userinfo');
        if($info){
            // 成功上传后 获取上传信息
            // echo $info->getExtension();
            echo $info->getSaveName();
            // echo $info->getFilename();
            $saveName = $info->getSaveName();
            $result = UserModel::where('id',session('id'))
                        ->update(['usericon' => '/images/userinfo/' . $saveName]);
            } else {
            // 上传失败获取错误信息
            echo $file->getError();
        }
        $this->redirect('info');
    }
    
    // 新增用户地址信息(最多添加5个地址)
    public function addressCheck()
    {   
        $historyAdd = db('address')->where('user_id',session('id'))->count();
        if ($historyAdd >= 5) {
            echo '地址已达上限，请删除后再添加新地址';
            exit;
        }
        $addAddress = new Address ([
                                        'user_id'        =>  session('id'),
                                        'username'  =>  session('name'),
                                        'name'      =>  input('post.name'),
                                        'phone'     =>  input('post.phone'),
                                        'city'      =>  input('post.city'),
                                        'address'   =>  input('post.address')
                                    ]);
        $addAddress->save();
        if ($addAddress) {
            echo "保存成功";
        } else {
            echo '保存失败';
        }
    }
    // 删除地址
    public function addressDel()
    {   
        $delAddress = Address::destroy(['id' => input('get.id')]);
        $this->redirect('address');
    }
    // 修改默认地址
    public function addressSet()
    {   
        // 查找所有相同user_id的id，修改ismain为0
        $userId = Db::name('address')->where('user_id',session('id'))->select();
        foreach ($userId as $key => $value) {
            $ismain = Db::name('address')
                        ->where('id', $value['id'])
                        ->update([
                        'ismain' => 0
                        ]);
        }
        // 更新选中的id的ismain值为1
        $result = Db::name('address')->where('id',input('get.id'))->update(['ismain' => '1']);
        $this->redirect('address');
    }
    // 更新地址
    public function addressUpdate()
    {
        var_dump($_POST);
        // $historyAdd = db('address')->where('user_id',session('id'))->count();
        // if ($historyAdd >= 5) {
        //     echo '地址已达上限，请删除后再添加新地址';
        //     exit;
        // }
        // echo "123";
        // echo (input('post.'));
        // exit;
        $addressUpdate = new Address;
        $addressUpdate->save([
                                'name'      =>  input('post.name'),
                                'phone'     =>  input('post.phone'),
                                'city'      =>  input('post.city'),
                               'address'   =>  input('post.address')
                                ],['id' => input('post.id')]);
        if ($addressUpdate) {
            echo "保存成功";
        } else {
            echo '保存失败';
        }
       
        // $addAddress = new Address ([
        //                                 'user_id'        =>  session('id'),
        //                                 'username'  =>  session('name'),
        //                                 'name'      =>  input('post.name'),
        //                                 'phone'     =>  input('post.phone'),
        //                                 'city'      =>  input('post.city'),
        //                                 'address'   =>  input('post.address')
        //                             ]);
        // $addAddress->save();
        // if ($addAddress) {
        //     echo "保存成功";
        // } else {
        //     echo '保存失败';
        // }
    }
}